package 动态规划.不同路径2;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/2/10 15:34
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        int[][] data = {{0,0,0},{1,1,1},{0,0,0}};
        System.out.println(uniquePathsWithObstacles(data));
    }

    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
        //起点就有障碍的话就直接返回0
        if (obstacleGrid[0][0] == 1){
            return 0;
        }
        //二维数组的行数
        int m = obstacleGrid.length;
        //二维数组的列数
        int n = obstacleGrid[0].length;

        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            if (obstacleGrid[i][0] == 0){
                dp[i][0] = 1;
            }else {
                //当障碍物出现在左边界和上边界时，分别要注意障碍物的右方和下放也应该是无路可走
                /*while (i < m){
                    dp[i][0] = 0;
                    i++;
                }*/
                //采用break即可，因为int型数组默认值为0
                break;
            }
        }
        for (int i = 0; i < n; i++) {
            if (obstacleGrid[0][i] == 0){
                dp[0][i] = 1;
            }else {
                break;
            }
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 0){
                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
                }else {
                    dp[i][j] = 0;
                }
            }
        }
        return dp[m-1][n-1];
    }


    //官方解法
    public static int uniquePathsWithObstacles2(int[][] obstacleGrid) {
        int n = obstacleGrid.length, m = obstacleGrid[0].length;
        int[] f = new int[m];

        f[0] = obstacleGrid[0][0] == 0 ? 1 : 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (obstacleGrid[i][j] == 1) {
                    f[j] = 0;
                    continue;
                }
                if (j - 1 >= 0 && obstacleGrid[i][j - 1] == 0) {
                    f[j] += f[j - 1];
                }
            }
        }

        return f[m - 1];
    }
}
